package com.glodon.paas.document.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.glodon.paas.document.api.bean.File;
import com.glodon.paas.document.biz.FileBiz;
import com.glodon.paas.document.biz.RevisionBiz;
import com.glodon.paas.document.constant.DocumentConstant;
import com.glodon.paas.document.dao.domain.FileInfoEntity;
import com.glodon.paas.document.service.RecyclerService;
import com.glodon.paas.document.service.util.DocumentPrivilege;
import com.glodon.paas.exception.PaasServerExceptionFactory;
import com.glodon.paas.exception.i18n.ErrorCode;

@Service("recyclerService")
public class RecyclerServiceImpl implements RecyclerService {

    @Autowired
    private FileBiz           fileBiz;

    @Autowired
    private RevisionBiz       revisionBiz;

    @Autowired
    private DocumentPrivilege privilege;

    @Override
    public RevisionBiz getRevisionBiz() {
        return revisionBiz;
    }

    @Override
    public File getFile(String userId, String fileId) {
        privilege.checkReadPrivilege(userId, fileId, true, true);
        return FileInfoEntity.getDto(fileBiz.getDeletedFile(fileId), false);
    }

    @Override
    public List<File> getFiles(String userId) {
        return FileInfoEntity.getDtos(fileBiz.getDeletedFiles(userId), false);
    }

    @Override
    public void remove(String userId, String fileId) {
        privilege.checkRemovePrivilege(userId, fileId, true, true);
        fileBiz.deleteFile(fileId);
    }

    @Override
    public void clean(String userId) {
        List<FileInfoEntity> files = fileBiz.getDeletedFiles(userId);
        if (files != null) {
            for (FileInfoEntity file : files) {
                fileBiz.deleteFile(file.getId());
            }
        }
    }

    @Override
    public List<String> restore(String userId, String fileId) {
        privilege.checkWritePrivilege(userId, fileId, true, true);
        FileInfoEntity file = fileBiz.getDeletedFile(fileId);
        if (file == null) {
            throw PaasServerExceptionFactory.notFoundException("can not find the deleted file[" + fileId + "]", null).setErrorCode(ErrorCode.FILE_NOT_EXIST);
        }
        if (DocumentConstant.FILE_STATUS_RECYCLE.intValue() == file.getDeletedStatus().intValue()) {
            return fileBiz.restore(fileId);
        } else {
            return new ArrayList<String>();
        }
    }

    @Override
    public List<File> getFiles(String userId, String fileName) {
        return FileInfoEntity.getDtos(fileBiz.getFiles(userId, fileName, new Integer[] {
                                              DocumentConstant.FILE_STATUS_RECYCLE,
                                              DocumentConstant.FILE_STATUS_RECYCLE_CASCADE }, null), false);
    }
}
